package net.bitacademy.java22.boundary;

// 로그인을 하기 위한 웹뷰를 구동하는 클레스

import net.bitacademy.java22.R;
import net.bitacademy.java22.domain.AccessTokenDAO;
import net.bitacademy.java22.service.GoogleCalendarAdapter;
import net.bitacademy.java22.service.Trigger;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class GoogleLogin extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Main.ActivityList.add(this);  //ActivityList에 GoogleLogin을 추가한다.
        
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Log.d("GoogleLogin", "in GoogleLogin");
        
        WebView webView = (WebView)this.findViewById(R.id.login);
        webView.setWebViewClient(new PascalWebViewClient(this));
        WebSettings webSettings = webView.getSettings();
        
        webView.setHorizontalScrollbarOverlay(true); //수평
        webView.setVerticalScrollbarOverlay(true); //수직
        
        webSettings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JsInterface(), "JsInterface");
		AccessTokenDAO accessTokenDAO = new AccessTokenDAO(this);     
		// DB에 이미 토큰이 있다면  --> 차후에 토큰이 유효한가에 대한 확인 필요. refresh와 연관됨
		if(accessTokenDAO.exist()){
			Log.d("accessTokenDAO.exist()", "true");
			webView.loadUrl("file:///android_asset/www/login.html");
		} else{
			Log.d("accessTokenDAO.exist()", "false");
			webView.loadUrl(GoogleCalendarAdapter.getInstance().getAuthorizationUrl());
		}		
    }
    
    //Activity 2개를 연결하는 부분입니다.(기준인 GoogleLogin에서 Main을 연결)
    private final class JsInterface {
        public void launchIntent(final String payload) {
        	GoogleLogin.this.runOnUiThread(new Runnable() {
              public void run() {
            	  GoogleLogin.this.startActivity(new Intent(GoogleLogin.this, Main.class));
            	  startService(new Intent(GoogleLogin.this, Trigger.class));
              }
           });
        }
     }       
    
}
